/**
  ******************************************************************************
  * @file    UDP_OpenClient.c
  * @author  exatron
  * @version V1.0.0
  * @date    segunda, 22 de dezembro de 2014
  * @brief   Função para abrir um socket client.
  ******************************************************************************
  * @attention
  *
  *
  ******************************************************************************
  */

/** @addtogroup TCP
  * @{
  */

/* Includes ------------------------------------------------------------------*/
#include "../../exatron/inc/common.h"

/* Private variables ---------------------------------------------------------*/
Socket_t sock;

/* External functions --------------------------------------------------------*/

/** @defgroup UDP_Functions
  * @{
  */

int main(int argc, char *argv[])
{
	char ip[100];
	int porta, n;

	int yes=1;

    if(argc < 3)
    {
        printf("\nUso: dg_client IP Porta\r\n\n");
        return 1;
    }

    bzero(ip, sizeof(ip));
	strcpy(ip, argv[1]);

	porta = atoi(argv[2]);

    bzero((char *)&sock,sizeof(sock));

    /* Abre o socket */
    sock.clifd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock.clifd < 0)
    {
		printf("Error on open socket\n\r");
		return 0;
    }

    /* Seta id e informações de endereço */
    sock.seraddr.sin_port = htons(porta);
    sock.seraddr.sin_family = AF_INET;
    sock.seraddr.sin_addr.s_addr = inet_addr(ip);

    if(setsockopt(sock.clifd,SOL_SOCKET,SO_BROADCAST,&yes,sizeof(int)) == -1)
    {
    	printf("Error on setsockopt\n\r");
    	exit(1);
    }

    fcntl(sock.clifd, F_SETFL, O_NONBLOCK);

	socklen_t clilen;
	clilen = sizeof(sock.cliaddr);

    while(1)
    {
    	bzero(sock.Data.buf_rx,RX_BUF_LEN);

    	printf("\nDigite uma menssagem: ");
    	fgets(sock.Data.buf_rx, RX_BUF_LEN, stdin);

    	n = 0;
    	while(n < strlen(sock.Data.buf_rx))
    	{
    		n += sendto(sock.clifd,sock.Data.buf_rx,strlen(sock.Data.buf_rx),0,(struct sockaddr *)&sock.seraddr,clilen);
    	}

    	bzero(sock.Data.buf_rx,RX_BUF_LEN);
    	n = 0;
    	do
    	{
    		n = recvfrom(sock.clifd,sock.Data.buf_rx,RX_BUF_LEN,0,(struct sockaddr *)&sock.seraddr,&clilen);
    	}while(n == -1);

    	printf("Recebi: %s\r\n", sock.Data.buf_rx);
    }
    close(sock.serfd);

    return 0;
}

/**
  * @}
  */

/**
  * @}
  */







